# @Author       : Xu Xiaokang
# @LastEditTime : 2025-08-29 23:49:13

# source "C:/_myJGY/17_Markdown/_myOpenSource/Vivado-Tcl/Non-Project-MB.tcl"
# Complete Non-Project Mode Script with Default Strategy Only

# 记录开始时间
set total_start_time [clock seconds]
set start_formatted_time [clock format $total_start_time -format "%Y-%m-%d %H:%M:%S"]

# 设置准确的源文件路径
set origin_dir "C:/Users/33553/Desktop/VivadoSpeedTest/2024.2/MB"
set output_dir [file join $origin_dir output]
# 创建输出目录
file mkdir $output_dir

#~ 设置器件 项目名称 顶层模块名 Block Design名 xdc名
set part_name "xc7a200tfbg676-2"
set prj_name MB
set top_module mb_preset_wrapper
set bd_name mb_preset
set use_xdc 1  ;# 1 表示需要读取，0 表示不需要
set xdc_name "top"

# 设置Vivado最大线程为32
set_param general.maxThreads 32

# 设置项目文件路径（使用file normalize确保路径正确）
set project_file [file normalize [file join $origin_dir ${prj_name}.xpr]]
set bd_file [file normalize [file join $origin_dir ${prj_name}.srcs sources_1 bd $bd_name ${bd_name}.bd]]
set wrapper_file [file normalize [file join $origin_dir ${prj_name}.srcs sources_1 imports hdl ${top_module}.v]]
if {$use_xdc} {
    set xdc_file [file normalize [file join $origin_dir ${prj_name}.srcs constrs_1 constrs $xdc_name.xdc]]
}

# 检查文件是否存在
proc check_file {file_path} {
    if {![file exists $file_path]} {
        puts "ERROR: File not found: $file_path"
        return 0
    }
    puts "INFO: Found file: $file_path"
    return 1
}

# 检查所有必需文件
if {![check_file $bd_file]}       {exit 1}
if {![check_file $wrapper_file]}  {exit 1}
if {$use_xdc} {
    if {![check_file $xdc_file]}  {exit 1}
}
if {![check_file $project_file]}  {exit 1}

#++ ==================== OOC模式生成 begin ====================
set ooc_start_time [clock seconds]

puts "INFO: Starting OOC mode generation..."

# 打开主项目
open_project $project_file

# 执行项目复位
puts "INFO: Resetting project..."
reset_project

# 生成所有目标文件
puts "INFO: Generating targets..."
generate_target all [get_files $bd_file]

# 导出IP用户文件
puts "INFO: Exporting IP user files..."
export_ip_user_files -of_objects [get_files $bd_file] -no_script -sync -force -quiet

# 创建IP运行
puts "INFO: Creating IP runs..."
create_ip_run [get_files -of_objects [get_fileset sources_1] $bd_file]

# 获取所有需要运行的IP合成运行
set ip_runs [get_runs *_synth_1]
puts "INFO: Found [llength $ip_runs] IP synthesis runs to launch"

# 启动所有IP合成运行
puts "INFO: Launching IP synthesis runs..."
launch_runs $ip_runs -jobs 32

# 等待所有IP合成运行完成
puts "INFO: Waiting for all IP synthesis runs to complete..."
foreach run $ip_runs {
    wait_on_run $run
    set run_status [get_property STATUS [get_runs $run]]
    puts "INFO: Run $run status: $run_status"

    # 检查运行是否成功
    if {![string match "*Complete*" $run_status] && ![string match "*complete*" $run_status]} {
        puts "ERROR: Run $run failed with status: $run_status"
    }
}

# 导出仿真文件
puts "INFO: Exporting simulation files..."
export_simulation -lib_map_path [list \
    {modelsim=./$prj_name.cache/compile_simlib/modelsim} \
    {questa=./$prj_name.cache/compile_simlib/questa} \
    {riviera=./$prj_name.cache/compile_simlib/riviera} \
    {activehdl=./$prj_name.cache/compile_simlib/activehdl}] \
    -of_objects [get_files $bd_file] \
    -directory "./$prj_name.ip_user_files/sim_scripts" \
    -ip_user_files_dir "./$prj_name.ip_user_files" \
    -ipstatic_source_dir "./$prj_name.ip_user_files/ipstatic" \
    -use_ip_compiled_libs -force -quiet

# 关闭项目
close_project

set ooc_elapsed_time [expr [clock seconds] - $ooc_start_time]
puts "INFO: OOC generation completed in $ooc_elapsed_time seconds"
#-- ==================== OOC模式生成 end ====================


#++ ==================== read_file begin ====================
set read_file_start_time [clock seconds]

puts "===================================="
puts "PHASE 1: READING SOURCE FILES"
puts "===================================="

read_bd $bd_file
read_verilog $wrapper_file

if {$use_xdc} {
    read_xdc $xdc_file
}

set read_file_elapsed_time [expr [clock seconds] - $read_file_start_time]
puts "INFO: read_file completed in $read_file_elapsed_time seconds"
#-- ==================== read_file end ====================


#++ ==================== Synth begin ====================
set Synth_start_time [clock seconds]

# 明确设置顶层模块（使用变量）
set_property TOP $top_module [current_fileset]

puts "============================================="
puts "PHASE 2: SYNTHESIS (Default Strategy)"
puts "============================================="

# 1.1 综合 - Synth Design (Default)
synth_design -top $top_module -part $part_name

# 1.1 Utilization - Synth Design (Default Report)
report_utilization -file ${output_dir}/Utilization_Synth_Design.rpt

# 1.2 Synthesis Report (由synth_design自动生成，在日志中查看)
puts "INFO: Synthesis Report generated in Vivado log"

write_checkpoint -force ${output_dir}/post_synth.dcp

set Synth_elapsed_time [expr [clock seconds] - $Synth_start_time]
puts "INFO: Synth completed in $Synth_elapsed_time seconds"
#-- ==================== Synth end ====================


#++ ==================== Impl begin ====================
set Impl_start_time [clock seconds]

puts "============================================"
puts "PHASE 3: IMPLEMENTATION (Default Strategy)"
puts "============================================"

# 2.2 Opt Design (opt_design) (Default)
opt_design

# 2.2 DRC - Opt Design (Default Report)
report_drc -file ${output_dir}/DRC_Opt_Design.rpt

# 2.4 Place Design (place_design) (Default)
place_design

# 2.4 IO - Place Design (Default Report)
report_io -file ${output_dir}/IO_Place_Design.rpt

# 2.4 Utilization - Place Design (Default Report)
report_utilization -file ${output_dir}/Utilization_Place_Design.rpt

# 2.4 Control Sets - Place Design (Default Report)
report_control_sets -verbose -file ${output_dir}/Control_Sets_Place_Design.rpt

# 2.6 Post-Place Phys Opt Design (phys_opt_design) (Default)
phys_opt_design

# 2.7 Route Design (route_design) (Default)
route_design

# 2.7 DRC - Route Design (Default Report)
report_drc -file ${output_dir}/DRC_Route_Design.rpt

# 2.7 Methodology - Route Design (Default Report)
report_methodology -file ${output_dir}/Methodology_Route_Design.rpt

# 2.7 Power - Route Design (Default Report)
report_power -file ${output_dir}/Power_Route_Design.rpt

# 2.7 Route Status - Route Design (Default Report)
report_route_status -file ${output_dir}/Route_Status_Route_Design.rpt

# 2.7 Timing Summary - Route Design (Default Report)
report_timing_summary -max_paths 10 -report_unconstrained -file ${output_dir}/Timing_Summary_Route_Design.rpt

# 2.7 Clock Utilization - Route Design (Default Report)
report_clock_utilization -file ${output_dir}/Clock_Utilization_Route_Design.rpt

# 2.7 Bus Skew - Route Design (Default Report)
report_bus_skew -warn_on_violation -file ${output_dir}/Bus_Skew_Route_Design.rpt

# 2.7 implementation log (由route_design自动生成，在日志中查看)
puts "INFO: Implementation log generated in Vivado log"

write_checkpoint -force ${output_dir}/post_route.dcp

set Impl_elapsed_time [expr [clock seconds] - $Impl_start_time]
puts "INFO: Implementation completed in $Impl_elapsed_time seconds"
#-- ==================== Impl end ====================


#++ ==================== Bitstream begin ====================
# 降低 DRC 检查的严重级别（谨慎使用）
set_property SEVERITY {Warning} [get_drc_checks NSTD-1]
set_property SEVERITY {Warning} [get_drc_checks UCIO-1]

set Bitstream_start_time [clock seconds]

puts "=================================================="
puts "PHASE 4: BITSTREAM GENERATION (Default Strategy)"
puts "=================================================="

# 2.9 Write Bitstream (Default) - 使用变量命名bit文件
write_bitstream -force ${output_dir}/${top_module}.bit

# 2.9 implementation log (由write_bitstream自动生成，在日志中查看)
puts "INFO: Bitstream implementation log generated in Vivado log"

set Bitstream_elapsed_time [expr [clock seconds] - $Bitstream_start_time]
puts "INFO: Bitstream completed in $Bitstream_elapsed_time seconds"
#-- ==================== Bitstream end ====================


#+++++++++++++++++++++++++ 最后信息输出 ++++++++++++++++++++++++++
set reprot_info "\n==================================="
append reprot_info "\nCOMPLETED - DEFAULT STRATEGY ONLY"
append reprot_info "\n==================================="
append reprot_info "\nTop Module: $top_module"
append reprot_info "\nGenerated DEFAULT reports only:"
append reprot_info "\n"
append reprot_info "\nSYNTHESIS PHASE:"
append reprot_info "\n- Utilization_Synth_Design.rpt (Default)"
append reprot_info "\n- Synthesis Report (自动生成，查看日志)"
append reprot_info "\n"
append reprot_info "\nIMPLEMENTATION PHASE - Default Report:"
append reprot_info "\n- DRC_Opt_Design.rpt"
append reprot_info "\n- IO_Place_Design.rpt"
append reprot_info "\n- Utilization_Place_Design.rpt"
append reprot_info "\n- Control_Sets_Place_Design.rpt"
append reprot_info "\n- DRC_Route_Design.rpt"
append reprot_info "\n- Methodology_Route_Design.rpt"
append reprot_info "\n- Power_Route_Design.rpt"
append reprot_info "\n- Route_Status_Route_Design.rpt"
append reprot_info "\n- Timing_Summary_Route_Design.rpt"
append reprot_info "\n- Clock_Utilization_Route_Design.rpt"
append reprot_info "\n- Bus_Skew_Route_Design.rpt"
append reprot_info "\n"
append reprot_info "\nNON-DEFAULT REPORTS (注释掉，可按需启用):"
append reprot_info "\n# Timing_Summary_Design_Initialization.rpt"
append reprot_info "\n# Timing_Summary_Opt_Design.rpt"
append reprot_info "\n# Incremental_Reuse_Place_Design.rpt"
append reprot_info "\n# Timing_Summary_Place_Design.rpt"
append reprot_info "\n# Timing_Summary_Post_Place_Phys_Opt_Design.rpt"
append reprot_info "\n# Incremental_Reuse_Route_Design.rpt"
append reprot_info "\n# Timing_Summary_Post_Route_Phys_Opt_Design.rpt"
append reprot_info "\n# Bus_Skew_Post_Route_Phys_Opt_Design.rpt"
append reprot_info "\n"
append reprot_info "\nBITSTREAM PHASE:"
append reprot_info "\n- ${top_module}.bit (生成的bit文件)"
append reprot_info "\n- implementation log (自动生成，查看日志)"
append reprot_info "\n"
append reprot_info "\nTotal: 11个Default Report文件生成"
append reprot_info "\n8个非Default Report已注释，可按需取消注释使用"
append reprot_info "\n================================"
append reprot_info "\n=================== COMPLETE TIME SUMMARY ==================="
append reprot_info "\nCompilation started:             $start_formatted_time"

# 最后一次性输出所有内容
puts $reprot_info

# ==================== 完整时间统计 ====================
set total_elapsed [expr [clock seconds] - $total_start_time]

set output "\n=================== COMPLETE TIME SUMMARY ==================="
append output "\nthis project name: $prj_name"
append output "\nCompilation started:             $start_formatted_time"
append output "\n=== PHASE 1: OOC Generation (Project Mode) ==="
append output "\nOOC generation:                  $ooc_elapsed_time seconds"
append output "\n=== PHASE 2: Non-Project ================="
append output "\nReading source files:            $read_file_elapsed_time seconds"
append output "\nSynthesis:                       $Synth_elapsed_time seconds"
append output "\nImplementation:                  $Impl_elapsed_time seconds"
append output "\nBitstream generation:            $Bitstream_elapsed_time seconds"
append output "\ntime total:                      [expr {
    $ooc_elapsed_time + $read_file_elapsed_time +
    $Synth_elapsed_time + $Impl_elapsed_time +
    $Bitstream_elapsed_time
}] seconds"
append output "\n=========================================================="
append output "\nTOTAL COMPILATION TIME:          $total_elapsed seconds"
append output "\n=========================================================="

puts $output
#--------------------------- 最后信息输出 ---------------------------